package com.rgs.se.data.queue;


import java.util.Arrays;

/**
 * @author Ren Gaoshuai
 * @ClassName LoopQueue
 * @date 2022-04-06 8:10
 **/
public class LoopQueue<E> implements MyQueue<E>{
    private int front,tail;
    private E[] data;
    private int size;

    public LoopQueue(){
        this(10);
    }

    public LoopQueue(int capacity){
        data = (E[])new Object[capacity+1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public int getCapacity(){
        return data.length-1;
    }
    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public void enQueue(E e) {
        //入队
        if ((tail+1) % data.length == front){
            //队列满
            //throw new IllegalArgumentException("队列满！");
            resize(getCapacity() << 1);
        }
        data[tail] = e;
        tail = (tail+1) % data.length;
        size++;
    }

    private void resize(int newCapacity){
        E[] newArr = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newArr[i] = data[(i+front) % data.length];
        }
        front = 0;
        data = newArr;
    }

    @Override
    public E deQueue() {
        //出队
        if (tail == front){
            //队列空
            throw new IllegalArgumentException("队列空！");
        }
        E old = data[front];
        data[front] = null;
        front = (front+1) % data.length;
        size--;
        return old;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列为空。");
        }
        return data[front];
    }



//    @Override
//    public String toString() {
//
//    }

    /**
     *
     *
     *
     * 时间复杂度
     * 出队 O1
     * 入队 O1
     */


}

